//package com.example.bluetooth;
//
//import android.Manifest;
//import android.bluetooth.BluetoothAdapter;
//import android.bluetooth.BluetoothDevice;
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.content.IntentFilter;
//import android.content.pm.PackageManager;
//import android.os.Build;
//import android.os.Handler;
//import android.os.Message;
//import android.support.v4.content.LocalBroadcastManager;
//import android.util.Log;
//import android.widget.TabHost;
//import android.widget.Toast;
//
//import com.alonginfo.app.plugin.dbcz.ble.manager.BluetoothControl;
//import com.alonginfo.app.plugin.dbcz.ble.service.BluetoothLeService;
//import com.alonginfo.app.plugin.dbcz.ble.utils.BluetoothControlUtil;
//import com.alonginfo.app.plugin.dbcz.ble.utils.DataProcessUtil;
//import com.alonginfo.app.plugin.dbcz.commonUtil.IBluetoothUtil;
//import com.alonginfo.app.plugin.dbcz.commonUtil.BleBluetoothUtil;
//
//import org.apache.cordova.CallbackContext;
//import org.apache.cordova.CordovaInterface;
//import org.apache.cordova.CordovaPlugin;
//import org.apache.cordova.CordovaWebView;
//import org.json.JSONArray;
//import org.json.JSONException;
//
//import java.lang.ref.WeakReference;
//
///**
// * This class echoes a string called from JavaScript.
// */
//public class DBCZ2 extends CordovaPlugin {
//    //蓝牙权限
//    public static final int REQUEST_OPEN_BT_CODE = 0x01;
//    private static final int REQUESTCODE_COARSE_LOCATION = 0x02;
//    private static final String PERMISSION_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;//"android.permission.ACCESS_COARSE_LOCATION";
//
//    private IBluetoothUtil bluetoothUtil;
//
//    private String TAG = "DBCZ2";
//
//    private static final String ACTION_LINK_BLUE_TOOTH = "action_link_blue_tooth";
//    private static final String ACTION_SEND_ORDER = "action_send_order";
//    private static final String ACTION_DISCONNECT_BLUETOOTH = "action_disconnect_bluetooth";
//    private CallbackContext callbackContext;
//    private BluetoothControl mBluetoothControl;
//
//    private long startLinkTime = 0;
//
//    /**
//     * 要连接的蓝牙MAC地址
//     */
//    private String addressToConnect;
//    /**
//     * 超时时间
//     */
//    private int connectTimeOut;
//    /**
//     * 主动断开蓝牙
//     */
//    private boolean disconnectByUser = false;
//    private int disconnectByUserOutTime = 5;
//    /**
//     * 断开蓝牙状态
//     */
//    private int disconnect_by_user_state = 0x00;
//    private static final int DISCONNECT_BY_USER_STATE_SUCCESS = 0x01;
//    private static final int DISCONNECT_BY_USER_STATE_ING = 0x00;
//
//    private BlueBroadcastReceiver mBlueBroadcastReciver;
//
//    @Override
//    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
//        this.callbackContext = callbackContext;
//        Log.i(TAG, action);
//        if (action.equals(ACTION_LINK_BLUE_TOOTH)) {
//            if (args == null || args.getString(0) == null || args.getString(0).length() == 0 || "null".equals(args.getString(0))) {
//                callbackContext.error("address null");
//                return true;
//            }
//            addressToConnect = args.getString(0).replaceAll(":", "").toUpperCase();
//            //addressToConnect 转为AB:CD:1E:2F:3G 格式
//            String reg = "(.{2})";
//            addressToConnect = addressToConnect.replaceAll(reg, "$0:");
//            addressToConnect = addressToConnect.substring(0, addressToConnect.length() - 1);
////            connectTimeOut=args.getInt(1);
//            connectTimeOut = connectTimeOut <= 0 ? 30 : connectTimeOut;//默认30秒
//
//            //如果需要在子线程执行
//            openBlueTooth(addressToConnect);
//            this.cordova.getThreadPool().execute(new Runnable() {
//                @Override
//                public void run() {
//                }
//            });
//            return true;
//        }
//        if (action.equals(ACTION_SEND_ORDER)) {
//            if (args == null || args.getString(0) == null || args.getString(0).length() == 0 || "null".equals(args.getString(0))) {
//                callbackContext.error("order null");
//                return true;
//            } else {
//                writeData(args.getString(0));
//            }
//            return true;
//        }
//
//        /*清除蓝牙连接*/
//        if (action.equals(ACTION_DISCONNECT_BLUETOOTH)) {
//            disConnect();
//            return true;
//        }
//        return false;
//    }
//
//
//    /**
//     * 写数据
//     *
//     * @param data
//     */
//    private void writeData(String data) {
//        if (BluetoothControlUtil.getInstance().getConnectState()) {
//            BluetoothControlUtil.getInstance().writeData(data.replaceAll(" ", ""), mHandler);
//        } else {
//            showToast("请先连接蓝牙设备");
//        }
//    }
//
//    /**
//     * 判断权限
//     * 打开蓝牙
//     * 尝试连接
//     *
//     * @param address
//     */
//    private void openBlueTooth(final String address) {
//        if (Build.VERSION.SDK_INT > 22 && !cordova.hasPermission(PERMISSION_COARSE_LOCATION)) {
//            cordova.requestPermission(this, REQUESTCODE_COARSE_LOCATION, PERMISSION_COARSE_LOCATION);
//            return;
//        }
//        if (bluetoothUtil == null) {
//            bluetoothUtil = new BleBluetoothUtil() {
//                @Override
//                public void onFoundDevices(BluetoothDevice device, int rssi, byte[] scanRecord) {
//                    if (device.getAddress().equals(address)) {
//                        if (isLinkTargetDevices(address)) {
//                            linkToDevices(device.getAddress());
//                        }
//                        bluetoothUtil.stopScan();
//                    }
//                }
//            };
//        }
//        if (bluetoothUtil.init(this.cordova.getActivity())) {
//            Log.d(TAG, "init success");
//        } else {
//            showToast("Your device does not support BLE bluetooth");
//            return;
//        }
//
//        if (!bluetoothUtil.isEnabled()) {
//            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            this.cordova.startActivityForResult(this, intent, REQUEST_OPEN_BT_CODE);
//        } else {
//            if (!isLinkTargetDevices(address)) {
//                bluetoothUtil.startScan();
//                startLinkTime = System.currentTimeMillis();
//                linkToDevices(address);
//                mHandler.postDelayed(new CheckConnectState(this), 500);
//            }
//        }
//    }
//
//    /**
//     * 判断当前给定的蓝牙地址是否已经连接
//     *
//     * @param address
//     * @return
//     */
//    public boolean isLinkTargetDevices(String address) {
//        if (!BluetoothControlUtil.getInstance().getConnectState())
//            return false;
//        if (!getCurrentAddress().equals(address)) {
//            BluetoothLeService.getInstance().disconnect();
//            return false;
//        } else {
//            this.callbackContext.success("success");
//            showToast("已经连接当前设备");
//            return true;
//        }
//    }
//
//    /**
//     * 尝试连接设备
//     *
//     * @param address
//     */
//    public void linkToDevices(final String address) {
//        this.cordova.getThreadPool().execute(new Runnable() {
//            @Override
//            public void run() {
//                if (getCurrentAddress().equals(address)) {
//                    if (!BluetoothControlUtil.getInstance().getConnectState()) {
//                        showToast("正在连接蓝牙设备");
//                        BluetoothLeService.getInstance().connect(address);
//                    }
//                    return;
//                }
//                showToast("正在连接蓝牙设备");
//                BluetoothControlUtil.getInstance().setCurrentAddress(address);
//                BluetoothLeService.getInstance().connect(address);
//            }
//        });
//    }
//
//    /**
//     * 获取当前连接的Mac地址，空返回""
//     *
//     * @return
//     */
//    public String getCurrentAddress() {
//        return BluetoothControlUtil.getInstance().getCurrentAddress() == null ? "" : BluetoothControlUtil.getInstance().getCurrentAddress();
//    }
//
//    /**
//     * 判断蓝牙是否打开了！
//     *
//     * @param requestCode The request code originally supplied to startActivityForResult(),
//     *                    allowing you to identify who this result came from.
//     * @param resultCode  The integer result code returned by the child activity through its setResult().
//     * @param intent      An Intent, which can return result data to the caller (various data can be
//     */
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//        if (requestCode == REQUEST_OPEN_BT_CODE) {
//            if (resultCode == 0) {//拒绝了蓝牙开启
//                showToast("连接蓝牙设备需要开启蓝牙");
//            } else if (resultCode == -1) {//蓝牙开启
//                openBlueTooth(addressToConnect);
//            }
//        }
//    }
//
//    private void showToast(final String msg) {
//        cordova.getActivity().runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(cordova.getActivity(), msg, Toast.LENGTH_SHORT).show();
//            }
//        });
//    }
//
//    private int PERMISSION_DENIED_ERROR = -1;
//
//    /**
//     * 判断权限
//     *
//     * @param requestCode
//     * @param permissions
//     * @param grantResults
//     * @throws JSONException
//     */
//    public void onRequestPermissionResult(int requestCode, String[] permissions,
//                                          int[] grantResults) throws JSONException {
//        for (int r : grantResults) {
//            if (r == PackageManager.PERMISSION_DENIED) {
//                // this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR));
//                showToast("获取权限失败");
//                return;
//            }
//        }
//        switch (requestCode) {
//            case REQUESTCODE_COARSE_LOCATION:
//                openBlueTooth(addressToConnect);
//                break;
//        }
//    }
//
//    @Override
//    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
//        super.initialize(cordova, webView);
//        initBluetooth();
//    }
//
//    private void registerBroadcast() {
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(BluetoothLeService.START_WRITE_SERVER);
//        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
//        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
//        LocalBroadcastManager.getInstance(this.cordova.getActivity()).registerReceiver(mBlueBroadcastReciver, intentFilter);
//    }
//
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        cleanUpBluetooth();
//    }
//
//
//    private void resetBluetooth() {
//        cleanUpBluetooth();
//        initBluetooth();
//    }
//
//    private void initBluetooth() {
//        BluetoothLeService.getInstance().init(cordova.getActivity());
//        if (mBluetoothControl == null) {
//            mBluetoothControl = new BluetoothControl();
//            mBluetoothControl.setOnSendResultListener(BluetoothControlUtil.getInstance());
//        }
//        //注册广播
//        mBluetoothControl.registerLocalBroadcast(cordova.getActivity());
//        if (!BluetoothLeService.getInstance().initialize()) {
//            showToast("不支持蓝牙设备");
//            return;
//        }
//        mBlueBroadcastReciver = new BlueBroadcastReceiver(this);
//        registerBroadcast();
//    }
//
//
//    private void disConnect() {
//        if (BluetoothControlUtil.getInstance().getConnectState()) {
//            disconnect_by_user_state = DISCONNECT_BY_USER_STATE_ING;
//            disconnectByUser = true;
//            mHandler.post(new CheckDisconnectState(this));
//            isAutoDis = false;
//            BluetoothLeService.getInstance().disconnect();
//            BluetoothLeService.getInstance().close();
//            BluetoothControlUtil.getInstance().setCurrentAddress(null);
//            BluetoothControlUtil.getInstance().setConnectState(false);
//        } else {
//            callbackContext.success("未连接，不需要断开");
//        }
//    }
//
//
//    private void cleanUpBluetooth() {
//        disConnect();
//        if (mBluetoothControl != null)
//            mBluetoothControl.unregisterLocalBroadcast(this.cordova.getActivity());
//        LocalBroadcastManager.getInstance(this.cordova.getActivity()).unregisterReceiver(mBlueBroadcastReciver);
//    }
//
//
//    private static class CheckDisconnectState implements Runnable {
//        private WeakReference<DBCZ2> weakReference;
//
//        public CheckDisconnectState(DBCZ2 dbcz2) {
//            this.weakReference = new WeakReference<DBCZ2>(dbcz2);
//        }
//
//        @Override
//        public void run() {
//            DBCZ2 dbcz2 = weakReference.get();
//            if (dbcz2 == null) return;
//            long startTime = System.currentTimeMillis();
//            while (dbcz2.disconnect_by_user_state == dbcz2.DISCONNECT_BY_USER_STATE_ING
//                && (System.currentTimeMillis() - startTime) < 1000 * dbcz2.disconnectByUserOutTime
//                &&  BluetoothControlUtil.getInstance().getConnectState()) {
//                try {
//                    Thread.sleep(20);
//                } catch (InterruptedException e) {
//                }
//            }
//            if (dbcz2.disconnect_by_user_state == dbcz2.DISCONNECT_BY_USER_STATE_SUCCESS || !BluetoothControlUtil.getInstance().getConnectState()) {
//                dbcz2.callbackContext.success("success");
//            } else {
//                dbcz2.callbackContext.error("error");
//            }
//            dbcz2.mHandler.removeCallbacks(this);
//        }
//    }
//
//    /**
//     * 判断蓝牙的连接
//     */
//    private static class CheckConnectState implements Runnable {
//        private WeakReference<DBCZ2> weakReference;
//
//        public CheckConnectState(DBCZ2 dbcz2) {
//            this.weakReference = new WeakReference<DBCZ2>(dbcz2);
//        }
//
//        @Override
//        public void run() {
//            DBCZ2 dbcz2 = weakReference.get();
//            if (dbcz2 == null) return;
//            if (dbcz2.startLinkTime == 0) {
//                dbcz2.startLinkTime = System.currentTimeMillis();
//            }
//            while (!BluetoothControlUtil.getInstance().getConnectState() && ((System.currentTimeMillis() - dbcz2.startLinkTime) < 1000 * dbcz2.connectTimeOut)) {
//                try {
//                    Thread.sleep(20);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//            //结束扫描
//            if (dbcz2.bluetoothUtil != null)
//                dbcz2.bluetoothUtil.stopScan();
//
//            if (!BluetoothControlUtil.getInstance().getConnectState()) {//没连接上,重置蓝牙，为下次连接做准备
//                dbcz2.callbackContext.error("error");
//                Log.e(dbcz2.TAG, "ERROR");
//                dbcz2.resetBluetooth();
//            } else {
//                dbcz2.callbackContext.success("success");
//            }
//            dbcz2.startLinkTime = 0;
//            //监控结束，回收掉
//            dbcz2.mHandler.removeCallbacks(this);
//        }
//    }
//
//
//    Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case BluetoothControl.READ_RESULT:
//                    final byte[] data = (byte[]) msg.obj;
//                    String strData = DataProcessUtil.getInstance().bytes2HexString(data);
//                    DBCZ2.this.callbackContext.success(strData);
//                    String newData = "";
//                    for (int i = 0; i < strData.length() / 2 - 1; i++) {
//                        newData = newData + strData.substring(i * 2, (i + 1) * 2) + " ";
//                    }
//                    newData = newData + strData.substring(strData.length() - 2, strData.length());
//                    Log.e(TAG, "new Data===" + newData);
//                    break;
//            }
//        }
//    };
//
//
//    private boolean isAutoDis = true;
//
//    private static class BlueBroadcastReceiver extends BroadcastReceiver {
//
//        private WeakReference<DBCZ2> weakReference;
//
//        public BlueBroadcastReceiver(DBCZ2 Dbcz) {
//            this.weakReference = new WeakReference<DBCZ2>(Dbcz);
//        }
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            DBCZ2 dbcz2 = weakReference.get();
//            if (dbcz2 == null) return;
//            String action = intent.getAction();
//
//            if (action.equals(BluetoothLeService.ACTION_GATT_CONNECTED)) {
//                Log.i(dbcz2.TAG, "ACTION_GATT_CONNECTED 蓝牙连接");
//            } else if (action.equals(BluetoothLeService.ACTION_GATT_DISCONNECTED)) {
//                if (dbcz2.isAutoDis)
//                    BluetoothLeService.getInstance().connect(BluetoothControlUtil.getInstance().getCurrentAddress());
//                BluetoothControlUtil.getInstance().setConnectState(false);
//                if (dbcz2.disconnectByUser) {
//                    dbcz2.disconnect_by_user_state = dbcz2.DISCONNECT_BY_USER_STATE_SUCCESS;
//                    dbcz2.disconnectByUser = false;
//                }else{
//                   dbcz2.showToast("蓝牙失去连接");
//                }
//            } else if (action.equals(BluetoothLeService.START_WRITE_SERVER)) {
//                BluetoothControlUtil.getInstance().setConnectState(true);
//                Log.i(dbcz2.TAG, "蓝牙准备就绪");
//                dbcz2.isAutoDis = true;
//                dbcz2.showToast("蓝牙连接成功");
//            }
//        }
//    }
//}
